<script setup lang="ts">
import { ref, onMounted, watch, computed, nextTick } from 'vue';
import { Table, Button, Select, Input, Popconfirm, message } from 'ant-design-vue';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { 
  getMenuListPermissions, 
  getTableFieldsByPermission,
  type MenuPermissionVo
} from '#/api/system/role';

interface DataScopeConfigItem {
  id?: number;
  menuId: number | null;
  menuName?: string;
  permission: string;
  filterField: string;
  filterValues: string;
  filterType: string;
  enableStatus: string;
}

// 使用从API模块导入的类型定义
type MenuPermission = MenuPermissionVo;

const props = defineProps<{
  value?: DataScopeConfigItem[];
}>();

const emit = defineEmits<{
  'update:value': [value: DataScopeConfigItem[]];
}>();

const configs = ref<DataScopeConfigItem[]>([]);
const menuPermissions = ref<MenuPermission[]>([]);
const loading = ref(false);
const fieldOptionsMap = ref<Record<number, string[]>>({});

// 过滤类型选项
const filterTypeOptions = [
  { label: '包含(IN)', value: 'IN' },
  { label: '等于(EQ)', value: 'EQ' },
  { label: '模糊匹配(LIKE)', value: 'LIKE' },
  { label: '不包含(NOT_IN)', value: 'NOT_IN' },
];

// 计算菜单选项
const menuOptions = computed(() => {
  console.log('==== 计算菜单选项 ====');
  console.log('menuPermissions.value:', menuPermissions.value);
  console.log('menuPermissions.value.length:', menuPermissions.value.length);
  
  if (!Array.isArray(menuPermissions.value)) {
    console.warn('menuPermissions.value 不是数组:', typeof menuPermissions.value);
    return [];
  }
  
  const options = menuPermissions.value.map(menu => {
    console.log('处理菜单项:', menu);
    return {
      label: menu.menuName,
      value: menu.menuId,
    };
  });
  console.log('计算后的菜单选项:', options);
  console.log('菜单选项数量:', options.length);
  return options;
});

// 获取指定菜单的权限选项
const getPermissionOptions = (menuId: number) => {
  const menu = menuPermissions.value.find(m => m.menuId === menuId);
  return menu?.permissions.map(p => ({
    label: p.permissionName,
    value: p.permission,
  })) || [];
};

// 表格列定义
const columns = [
  {
    title: '菜单',
    dataIndex: 'menuId',
    width: 160,
    minWidth: 160,
    key: 'menuId',
  },
  {
    title: '接口权限',
    dataIndex: 'permission',
    width: 220,
    minWidth: 220,
    key: 'permission',
  },
  {
    title: '过滤字段',
    dataIndex: 'filterField',
    width: 140,
    minWidth: 140,
    key: 'filterField',
  },
  {
    title: '过滤值',
    dataIndex: 'filterValues',
    width: 250,
    minWidth: 250,
    key: 'filterValues',
  },
  {
    title: '过滤类型',
    dataIndex: 'filterType',
    width: 140,
    minWidth: 140,
    key: 'filterType',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 90,
    minWidth: 90,
    key: 'action',
  },
];

// 加载菜单列表权限
async function loadMenuPermissions() {
  try {
    loading.value = true;
    console.log('开始加载菜单权限...');
    const response = await getMenuListPermissions();
    console.log('API完整响应:', response);
    
    // 根据HTTP客户端的响应拦截器逻辑，成功时直接返回的就是数据
    // 如果返回的是数组，直接使用；如果是对象，尝试获取不同字段
    let data: MenuPermissionVo[] = [];
    
    if (Array.isArray(response)) {
      // 响应直接是数组
      data = response as MenuPermissionVo[];
      console.log('响应是数组，直接使用:', data);
    } else if (response && typeof response === 'object') {
      // 响应是对象，尝试多种可能的字段
      const responseObj = response as any;
      if (responseObj.data && Array.isArray(responseObj.data)) {
        data = responseObj.data as MenuPermissionVo[];
        console.log('从response.data获取:', data);
      } else if (responseObj.list && Array.isArray(responseObj.list)) {
        data = responseObj.list as MenuPermissionVo[];
        console.log('从response.list获取:', data);
      } else if (responseObj.rows && Array.isArray(responseObj.rows)) {
        data = responseObj.rows as MenuPermissionVo[];
        console.log('从response.rows获取:', data);
      } else {
        // 如果对象没有明确的数据字段，检查是否整个对象就是数据
        console.log('对象的所有键:', Object.keys(responseObj));
        // 如果响应对象本身可能就是我们需要的数据，先尝试直接使用
        if (Array.isArray(responseObj)) {
          data = responseObj as MenuPermissionVo[];
        }
        console.log('使用整个响应对象作为数据:', data);
      }
    }
    
    console.log('最终提取的数据:', data);
    console.log('数据类型:', typeof data);
    console.log('是否为数组:', Array.isArray(data));
    
    // 确保数据是数组格式
    if (Array.isArray(data)) {
      menuPermissions.value = data;
    } else {
      console.warn('提取的数据不是数组格式:', data);
      menuPermissions.value = [];
    }
    
    console.log('设置后的菜单权限数据:', menuPermissions.value);
    console.log('菜单权限数据长度:', menuPermissions.value.length);
  } catch (error) {
    console.error('加载菜单权限失败:', error);
    message.error('加载菜单权限失败');
  } finally {
    loading.value = false;
  }
}

// 添加新配置行
function addConfig() {
  const newConfig: DataScopeConfigItem = {
    menuId: null as any, // 避免显示"0"
    permission: '',
    filterField: '',
    filterValues: '',
    filterType: 'IN',
    enableStatus: '0',
  };
  configs.value.push(newConfig);
  console.log('==== 添加新配置后 ====');
  console.log('当前配置数量:', configs.value.length);
  console.log('所有配置:', JSON.stringify(configs.value, null, 2));
  console.log('菜单选项可用性:', menuOptions.value.length);
  updateValue();
}

// 删除配置行
function removeConfig(index: number) {
  console.log('==== 删除配置行开始 ====');
  console.log('删除索引:', index);
  console.log('删除前配置数量:', configs.value.length);
  console.log('删除前所有配置:', JSON.stringify(configs.value, null, 2));
  
  if (index < 0 || index >= configs.value.length) {
    console.error('删除索引无效:', index, '配置总数:', configs.value.length);
    message.error('删除失败：索引无效');
    return;
  }
  
  try {
    // 保存被删除的配置信息用于日志
    const deletedConfig = configs.value[index];
    console.log('即将删除的配置:', JSON.stringify(deletedConfig, null, 2));
    
    // 删除指定索引的配置
    configs.value.splice(index, 1);
    console.log('数组splice操作完成，当前数量:', configs.value.length);
    
    // 清理字段选项映射
    console.log('清理字段选项映射，删除索引:', index);
    delete fieldOptionsMap.value[index];
    
    // 重新整理映射索引
    const newFieldOptionsMap: Record<number, string[]> = {};
    Object.keys(fieldOptionsMap.value).forEach(key => {
      const keyIndex = parseInt(key);
      if (keyIndex > index) {
        newFieldOptionsMap[keyIndex - 1] = fieldOptionsMap.value[keyIndex];
      } else if (keyIndex < index) {
        newFieldOptionsMap[keyIndex] = fieldOptionsMap.value[keyIndex];
      }
    });
    fieldOptionsMap.value = newFieldOptionsMap;
    
    console.log('删除后配置数量:', configs.value.length);
    console.log('删除后所有配置:', JSON.stringify(configs.value, null, 2));
    console.log('更新后的字段选项映射:', fieldOptionsMap.value);
    
    // 通知父组件数据变化
    updateValue();
    console.log('已调用updateValue通知父组件');
    
    message.success(`删除配置成功，当前还有${configs.value.length}条配置`);
    
  } catch (error) {
    console.error('删除配置时发生错误:', error);
    message.error('删除配置时发生错误：' + error.message);
  }
  
  console.log('==== 删除配置行结束 ====');
}

// 获取指定索引的字段选项
const getFieldOptions = (index: number) => {
  const fields = fieldOptionsMap.value[index] || [];
  console.log(`获取字段选项 index:${index}, 原始字段:`, fields);
  const options = fields.map(field => ({
    label: field,
    value: field,
  }));
  console.log(`字段选项 index:${index}, 转换后:`, options);
  return options;
};

// 菜单选择变化
function handleMenuChange(menuId: number, index: number) {
  const config = configs.value[index];
  if (config) {
    config.menuId = menuId;
    config.permission = ''; // 重置权限选择
    
    // 设置菜单名称
    const menu = menuPermissions.value.find(m => m.menuId === menuId);
    if (menu) {
      config.menuName = menu.menuName;
    }
  }
  updateValue();
}

// 权限选择变化
async function handlePermissionChange(permission: string, index: number) {
  console.log('权限选择变化:', permission, 'index:', index);
  const config = configs.value[index];
  if (config) {
    config.permission = permission;
    config.filterField = ''; // 重置字段选择
    
    // 获取对应的表字段选项
    if (permission) {
      try {
        console.log('开始获取表字段，权限标识:', permission);
        const response = await getTableFieldsByPermission(permission);
        console.log('表字段API响应:', response);
        
        // 使用和菜单数据相同的提取逻辑
        let fields = null;
        if (Array.isArray(response)) {
          fields = response;
          console.log('响应是数组，直接使用:', fields);
        } else if (response && typeof response === 'object') {
          if (response.data) {
            fields = response.data;
            console.log('从response.data获取字段:', fields);
          } else if (response.list) {
            fields = response.list;
            console.log('从response.list获取字段:', fields);
          } else if (response.rows) {
            fields = response.rows;
            console.log('从response.rows获取字段:', fields);
          } else {
            console.log('对象的所有键:', Object.keys(response));
            fields = response;
            console.log('使用整个响应对象作为字段数据:', fields);
          }
        }
        
        console.log('最终提取的字段数据:', fields);
        console.log('字段数据类型:', typeof fields);
        console.log('是否为数组:', Array.isArray(fields));
        
        if (Array.isArray(fields)) {
          fieldOptionsMap.value[index] = fields;
          console.log('设置字段选项映射 index:', index, 'fields:', fields);
        } else {
          console.warn('提取的字段数据不是数组格式:', fields);
          fieldOptionsMap.value[index] = [];
        }
        
        console.log('当前fieldOptionsMap:', fieldOptionsMap.value);
      } catch (error) {
        console.error('获取表字段失败:', error);
        fieldOptionsMap.value[index] = [];
        message.error('获取表字段失败');
      }
    } else {
      fieldOptionsMap.value[index] = [];
    }
  }
  updateValue();
}

// 字段变化
function handleFieldChange(field: string, value: any, index: number) {
  const config = configs.value[index];
  if (config) {
    config[field as keyof DataScopeConfigItem] = value;
  }
  updateValue();
}

// 更新值
function updateValue() {
  console.log('==== updateValue 被调用 ====');
  console.log('当前configs.value:', configs.value);
  console.log('即将emit的数据:', [...configs.value]);
  
  const dataToEmit = [...configs.value];
  emit('update:value', dataToEmit);
  
  // 额外确保数据传递，使用nextTick
  nextTick(() => {
    console.log('nextTick后再次emit数据');
    emit('update:value', [...configs.value]);
  });
}

// 验证必填字段
function validateRequired(record: DataScopeConfigItem, field: string): boolean {
  switch (field) {
    case 'menuId':
      return !record.menuId || record.menuId === null; // 菜单是必填的
    case 'permission':
      return !record.permission || record.permission.trim() === ''; // 接口权限是必填的
    case 'filterField':
      return !record.filterField || record.filterField.trim() === ''; // 过滤字段是必填的
    case 'filterValues':
      return !record.filterValues || record.filterValues.trim() === ''; // 过滤值是必填的
    default:
      return false;
  }
}

// 获取字段验证状态的CSS类
function getValidationClass(record: DataScopeConfigItem, field: string): string {
  return validateRequired(record, field) ? 'field-error' : '';
}

// 检查整个配置是否有验证错误
function hasValidationErrors(): boolean {
  console.log('==== 开始验证数据权限配置 ====');
  console.log('配置数量:', configs.value.length);
  console.log('配置数据:', JSON.stringify(configs.value, null, 2));
  
  if (configs.value.length === 0) {
    console.log('没有配置项');
    return false; // 没有配置项时不算错误，在父组件中检查
  }
  
  const hasErrors = configs.value.some((config, index) => {
    const menuIdError = validateRequired(config, 'menuId');
    const permissionError = validateRequired(config, 'permission');
    const filterFieldError = validateRequired(config, 'filterField');
    const filterValuesError = validateRequired(config, 'filterValues');
    
    const configHasError = menuIdError || permissionError || filterFieldError || filterValuesError;
    
    console.log(`配置项 ${index + 1}:`, {
      data: {
        menuId: config.menuId,
        menuName: config.menuName,
        permission: config.permission,
        filterField: config.filterField,
        filterValues: config.filterValues,
        filterType: config.filterType
      },
      errors: {
        menuIdError,
        permissionError,
        filterFieldError,
        filterValuesError
      },
      hasError: configHasError
    });
    
    return configHasError;
  });
  
  console.log('==== 验证结果:', hasErrors ? '有错误' : '无错误', '====');
  return hasErrors;
}

// 初始化数据
function initData() {
  if (props.value && Array.isArray(props.value)) {
    configs.value = [...props.value];
  } else {
    configs.value = [];
  }
}

// 监听props变化
watch(
  () => props.value,
  () => {
    initData();
  },
  { deep: true, immediate: true }
);

onMounted(() => {
  console.log('==== DataScopeConfig 组件已挂载 ====');
  loadMenuPermissions();
});

// 监听菜单数据变化
watch(
  () => menuPermissions.value,
  (newValue, oldValue) => {
    console.log('==== 菜单权限数据变化 ====');
    console.log('旧值:', oldValue?.length || 0);
    console.log('新值:', newValue?.length || 0);
    console.log('新数据:', newValue);
  },
  { deep: true }
);

// 测试函数：用于调试表单状态
function debugFormState() {
  console.log('==== 表单调试信息 ====');
  console.log('配置数量:', configs.value.length);
  console.log('菜单选项数量:', menuOptions.value.length);
  console.log('加载状态:', loading.value);
  console.log('菜单权限数据:', menuPermissions.value);
  console.log('所有配置项:');
  configs.value.forEach((config, index) => {
    console.log(`配置 ${index}:`, {
      menuId: config.menuId,
      menuName: config.menuName,
      permission: config.permission,
      filterField: config.filterField,
      filterValues: config.filterValues,
      filterType: config.filterType,
      enableStatus: config.enableStatus
    });
  });
  
  // 测试验证结果
  const hasErrors = hasValidationErrors();
  console.log('整体验证结果:', hasErrors);
  
  return {
    configs: configs.value,
    menuOptions: menuOptions.value,
    hasErrors,
    loading: loading.value
  };
}

// 暴露验证函数给父组件
defineExpose({
  hasValidationErrors,
  validateRequired,
  debugFormState, // 暴露调试函数
});
</script>

<template>
  <div class="data-scope-config">
    <div class="mb-4">
      <Button type="primary" @click="addConfig">
        <PlusOutlined />
        添加权限配置
      </Button>
    </div>
    
    <Table
      :columns="columns"
      :data-source="configs"
      :pagination="false"
      size="small"
      bordered
      :scroll="{ x: 1200 }"
      :row-key="(record, index) => index"
      table-layout="fixed"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'menuId'">
          <div style="min-width: 160px;">
            <Select
              v-model:value="record.menuId"
              placeholder="选择菜单"
              style="width: 100%"
              :options="menuOptions"
              :class="getValidationClass(record, 'menuId')"
              :status="validateRequired(record, 'menuId') ? 'error' : ''"
              :loading="loading"
              :not-found-content="menuOptions.length === 0 ? '暂无菜单数据' : undefined"
              show-search
              filter-option
              @change="(value) => handleMenuChange(value, index)"
              @click="() => console.log('菜单选择器被点击, 当前选项:', menuOptions, '当前值:', record.menuId)"
              @dropdown-visible-change="(open) => console.log('菜单下拉框状态:', open, '选项数量:', menuOptions.length)"
            />
            <div v-if="validateRequired(record, 'menuId')" class="error-text">
              请选择菜单
            </div>
            <div v-if="!loading && menuOptions.length === 0" class="error-text">
              菜单数据加载失败，请刷新页面重试
            </div>
          </div>
        </template>
        
        <template v-else-if="column.dataIndex === 'permission'">
          <div style="min-width: 220px;">
            <Select
              v-model:value="record.permission"
              placeholder="选择接口"
              style="width: 100%"
              :options="getPermissionOptions(record.menuId)"
              :disabled="!record.menuId"
              :class="getValidationClass(record, 'permission')"
              :status="validateRequired(record, 'permission') ? 'error' : ''"
              :not-found-content="!record.menuId ? '请先选择菜单' : '暂无接口权限'"
              show-search
              filter-option
              @change="(value) => handlePermissionChange(value, index)"
              @click="() => console.log('接口权限选择器被点击, 菜单ID:', record.menuId, '权限选项:', getPermissionOptions(record.menuId))"
            />
            <div v-if="validateRequired(record, 'permission')" class="error-text">
              请选择接口权限
            </div>
          </div>
        </template>
        
        <template v-else-if="column.dataIndex === 'filterField'">
          <div style="min-width: 140px;">
            <Select
              v-model:value="record.filterField"
              placeholder="选择字段"
              style="width: 100%"
              :options="getFieldOptions(index)"
              :disabled="!record.permission"
              :class="getValidationClass(record, 'filterField')"
              :status="validateRequired(record, 'filterField') ? 'error' : ''"
              :not-found-content="!record.permission ? '请先选择接口权限' : '暂无字段数据'"
              show-search
              filter-option
              @change="(value) => handleFieldChange('filterField', value, index)"
            />
            <div v-if="validateRequired(record, 'filterField')" class="error-text">
              请选择过滤字段
            </div>
          </div>
        </template>
        
        <template v-else-if="column.dataIndex === 'filterValues'">
          <div style="min-width: 250px;">
            <Input
              v-model:value="record.filterValues"
              placeholder='["值1","值2"]'
              style="width: 100%"
              :class="getValidationClass(record, 'filterValues')"
              :status="validateRequired(record, 'filterValues') ? 'error' : ''"
              @change="(e) => handleFieldChange('filterValues', e.target.value, index)"
              @blur="() => console.log('过滤值输入完成:', record.filterValues)"
            />
            <div v-if="validateRequired(record, 'filterValues')" class="error-text">
              请填写过滤值
            </div>
          </div>
        </template>
        
        <template v-else-if="column.dataIndex === 'filterType'">
          <div style="min-width: 140px;">
            <Select
              v-model:value="record.filterType"
              style="width: 100%"
              :options="filterTypeOptions"
              @change="(value) => handleFieldChange('filterType', value, index)"
            />
          </div>
        </template>
        
        <template v-else-if="column.dataIndex === 'action'">
          <Popconfirm
            title="确定删除此配置吗？"
            @confirm="() => removeConfig(index)"
            @cancel="() => console.log('取消删除配置', index)"
          >
            <Button 
              type="text" 
              danger 
              size="small"
              @click="() => console.log('点击删除按钮，索引:', index, '配置总数:', configs.length)"
            >
              <DeleteOutlined />
            </Button>
          </Popconfirm>
        </template>
      </template>
    </Table>
    
    <div v-if="configs.length === 0" class="text-center py-8 text-gray-400">
      暂无配置，点击上方按钮添加权限配置
    </div>
  </div>
</template>

<style scoped>
.data-scope-config {
  min-height: 200px;
  width: 100%;
}

:deep(.ant-table) {
  width: 100%;
}

:deep(.ant-table-cell) {
  padding: 8px 6px !important;
  white-space: nowrap;
}

:deep(.ant-select) {
  min-width: 140px;
  width: 100%;
}

:deep(.ant-input) {
  min-width: 120px;
  width: 100%;
  border-color: inherit !important;
}

:deep(.ant-table-tbody .ant-table-cell) {
  vertical-align: top;
}

.field-error {
  border-color: #ff4d4f !important;
  box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.2) !important;
}

.error-text {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 2px;
  line-height: 1.2;
  word-break: break-word;
}

:deep(.ant-select-selector.ant-select-selector) {
  border-color: inherit !important;
}

/* 响应式表格 */
:deep(.ant-table-wrapper) {
  overflow-x: auto;
}

/* 表格列宽优化 */
:deep(.ant-table-thead .ant-table-cell:nth-child(1)), 
:deep(.ant-table-tbody .ant-table-cell:nth-child(1)) { /* 菜单 */
  min-width: 160px !important;
  width: 160px !important;
}

:deep(.ant-table-thead .ant-table-cell:nth-child(2)), 
:deep(.ant-table-tbody .ant-table-cell:nth-child(2)) { /* 接口权限 */
  min-width: 220px !important;
  width: 220px !important;
}

:deep(.ant-table-thead .ant-table-cell:nth-child(3)), 
:deep(.ant-table-tbody .ant-table-cell:nth-child(3)) { /* 过滤字段 */
  min-width: 140px !important;
  width: 140px !important;
}

:deep(.ant-table-thead .ant-table-cell:nth-child(4)), 
:deep(.ant-table-tbody .ant-table-cell:nth-child(4)) { /* 过滤值 */
  min-width: 250px !important;
  width: 250px !important;
}

:deep(.ant-table-thead .ant-table-cell:nth-child(5)), 
:deep(.ant-table-tbody .ant-table-cell:nth-child(5)) { /* 过滤类型 */
  min-width: 140px !important;
  width: 140px !important;
}

:deep(.ant-table-thead .ant-table-cell:nth-child(6)), 
:deep(.ant-table-tbody .ant-table-cell:nth-child(6)) { /* 操作 */
  min-width: 90px !important;
  width: 90px !important;
}
</style>